package com.cxb.manager;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.cxb.utils.Constants;
import com.cxb.utils.SharedPreferencesUtils;
import com.cxb.utils.Constants.Setting;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;

/**
 * @author Tomy Created by Tomy on 14-2-26.
 */
public class WifiApManager {
	private static final String TAG = "WifiApHandler: ";
	private SharedPreferencesUtils spPreferencesUtils;
	// public static final String ACTION_TETHER_STATE_CHANGED =
	// "android.net.conn.TETHER_STATE_CHANGED";
	public static final String WIFI_AP_STATE_CHANGED_ACTION = "android.net.wifi.WIFI_AP_STATE_CHANGED";
	public static int WIFI_AP_UPDATE_CONFIG = 0x1001;
	public static int WIFI_AP_UPDATE_ERROR = 0x1002;
	public static int WIFI_AP_UPDATE_CHECKBOX = 0x1003;
	private String EXTRA_WIFI_AP_STATE = "";
	public static final int WIFI_AP_DISABLED = -1;
	public static final int WIFI_AP_ENABLED = 0;
	private WifiManager mWifiManager = null;
	private Context mContext = null;
	
	private WifiConfiguration mWifiConfig = null;
	private OnWifiApStateChangedListener mWifiApStateListener = null;
	private Method mMethodSetWifiAp = null;
	private IntentFilter mIntentFilter = null;

	public WifiApManager(Context mContext) {
		this.mContext = mContext;
		spPreferencesUtils = new SharedPreferencesUtils(mContext);
		mWifiManager = (WifiManager) mContext
				.getSystemService(Context.WIFI_SERVICE);
		setConfigDefault();
		initMethod();
		mIntentFilter = new IntentFilter(WIFI_AP_STATE_CHANGED_ACTION);
		mIntentFilter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
	}

	public void registerWifiApStateChangedListener(
			OnWifiApStateChangedListener listener) {
		mWifiApStateListener = listener;
		registerReceiver();
	}

	public void registerReceiver() {
		Log.d(TAG, "registerReceiver()");
		mContext.registerReceiver(mReceiver, mIntentFilter);
	}

	public void unregisterReceiver() {
		Log.d(TAG, "unregisterReceiver()");
		mContext.unregisterReceiver(mReceiver);
	}

	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (WIFI_AP_STATE_CHANGED_ACTION.equals(action)) {

				mWifiApStateListener.onWifiApStateChanged(intent.getIntExtra(
						EXTRA_WIFI_AP_STATE, Constants.WIFI_AP_STATE_FAILED));
			}

		}
	};

	public void setWifiApConfiguration(WifiConfiguration configuration) {
		mWifiConfig = configuration;
	}

	public void setConfigDefault() {
		mWifiConfig = new WifiConfiguration();
		mWifiConfig.SSID = spPreferencesUtils.getWifiApSSID();
		mWifiConfig.preSharedKey = spPreferencesUtils.getWifiApPassword();

		mWifiConfig.allowedAuthAlgorithms
				.set(WifiConfiguration.AuthAlgorithm.OPEN);
		mWifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
		mWifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
		mWifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
		mWifiConfig.allowedPairwiseCiphers
				.set(WifiConfiguration.PairwiseCipher.CCMP);
		mWifiConfig.allowedPairwiseCiphers
				.set(WifiConfiguration.PairwiseCipher.TKIP);
		mWifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
		mWifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
	}

	public void closeWifiAp() {
		try {
			if (isWifiApEnabled()) {
				mMethodSetWifiAp.invoke(mWifiManager, mWifiConfig, false);
				spPreferencesUtils.setWifiApEnable(false);
			}
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		// if (!mWifiManager.isWifiEnabled()) {
		// mWifiManager.setWifiEnabled(true);
		// }
	}

	public void changeWifiApState(boolean isOpened) {
		if (!isOpened) {
			closeWifiAp();
		} else {
			openWifiAp();
		}
	}

	public void initMethod() {
		try {
			if (mMethodSetWifiAp == null) {
				mMethodSetWifiAp = mWifiManager.getClass().getMethod(
						METHOD_SET_WIFI_AP_ENABLE, WifiConfiguration.class,
						Boolean.TYPE);
			}
			EXTRA_WIFI_AP_STATE = (String) mWifiManager.getClass()
					.getDeclaredField("EXTRA_WIFI_AP_STATE").get(mWifiManager);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void openWifiAp() {
		if (mWifiManager.isWifiEnabled()) {
			mWifiManager.setWifiEnabled(false);
		}
		try {
			Settings.System.putInt(mContext.getContentResolver(),
					"wifi_hotspot_auto_disable", 0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			// 不超时

			mMethodSetWifiAp.invoke(mWifiManager, mWifiConfig, true);
			spPreferencesUtils.setWifiApEnable(true);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}

	public boolean isWifiApEnabled() {
		try {
			Method method = mWifiManager.getClass().getMethod(
					METHOD_IS_WIFI_AP_ENABLED);
			method.setAccessible(true);
			return (Boolean) method.invoke(mWifiManager);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public static final String METHOD_SET_WIFI_AP_ENABLE = "setWifiApEnabled";
	public static final String METHOD_IS_WIFI_AP_ENABLED = "isWifiApEnabled";

	public interface OnWifiApStateChangedListener {
		public void onWifiApStateChanged(int wifiApState);
	}
}
